package com.mlamp.链表;

public class 相交链表 {

    public static void main(String[] args) {

    }


    public ListNode getInterSectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pa = headA, pb = headB;
        while (pa != pb) {
            pa = pa == null ? headB : pa.next;
            pb = pb == null ? headA : pb.next;
        }
        return pa;
    }


    /**
     * 判断两个链表相交
     *
     * @param headA
     * @param headB
     * @return
     */

    public ListNode getInterSectionNodeC(ListNode headA,
                                         ListNode headB) {
        assert headA != null && headB != null;
        ListNode pa = headA, pb = headB;
        while (pa != pb) {
            pa = pa == null ? headB : pa.next;
            pb = pb == null
                    ? headA : pb.next;
        }
        return pa;
    }


    public ListNode getInterSectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pa = headA, pb = headB;
        while (pa != pb) {
            pa = pa == null ? headB : pa.next;
            pb = pb == null ? headA : pb.next;
        }
        return pa;
    }


    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }


    public ListNode getInterSectionNodeA(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pa = headA, pB = headB;
        while (pa != pB) {
            pa = pa == null ? headB : pa.next;
            pB = pB == null ? headB : pB.next;
        }
        return pa;
    }


    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
